package cn.hu.basic.service.impl;

import cn.hu.basic.commonenum.ErrorCode;
import cn.hu.basic.constants.Constant;
import cn.hu.basic.domain.dto.LoginDto;
import cn.hu.basic.domain.dto.WeChatBinderDto;
import cn.hu.basic.exception.CustomException;
import cn.hu.basic.jwt.JwtUtils;
import cn.hu.basic.jwt.RsaUtils;
import cn.hu.basic.jwt.UserInfo;
import cn.hu.basic.service.ILoginService;
import cn.hu.basic.util.AjaxResult;
import cn.hu.basic.util.HttpClientUtils;
import cn.hu.basic.util.MD5Utils;
import cn.hu.basic.util.StrUtils;
import cn.hu.system.domain.Menu;
import cn.hu.system.mapper.MenuMapper;
import cn.hu.system.mapper.PermissionMapper;
import cn.hu.user.domain.Logininfo;
import cn.hu.user.domain.User;
import cn.hu.user.domain.Wxuser;
import cn.hu.user.mapper.LogininfoMapper;
import cn.hu.user.mapper.UserMapper;
import cn.hu.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")// SPEL表达式读取配置文件中的值
    private String jwtRsaPrivate;

    @Override
    public AjaxResult usernameLogin(LoginDto dto) {
        //先查有没有这个人
        Logininfo lf = logininfoMapper.findByAccountandType(dto.getAccount(),dto.getType());
        if(lf==null){//不存在抛异常
            throw new CustomException(ErrorCode.LOGIN_FAILED.getCode());
        }
        //存在就校验输入的密码
        String passwordFromUser = MD5Utils.encrypByMd5(lf.getSalt() + dto.getPassword());
        if (!passwordFromUser.equals(lf.getPassword())){
            throw new CustomException(ErrorCode.LOGIN_FAILED.getCode());
        }
//        //校验通过，设置uuid和logininfo存到redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,lf,30, TimeUnit.MINUTES);
//        //组装数据返回给前端(map组装数据)
//        HashMap<String, Object> hm = new HashMap<>();
//        hm.put("token",token);
//        //处理logininfo
//        lf.setType(null);
//        lf.setPassword(null);
//        lf.setSalt(null);
//        lf.setDisable(null);
//        hm.put("logininfo",lf);
        return AjaxResult.getInstance().setResultObject(loginSuccessHandler(lf));
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //校验code是否传过来
        String code = map.get("code");
        if(code==null){
            throw new CustomException(ErrorCode.WECHAT_LOGIN_FAILED.getCode());
        }
        //通过code请求微信获取token
        String getTokenUrl = Constant.WeChat.GET_TOKEN
                .replace("APPID", Constant.WeChat.APPID)
                .replace("SECRET", Constant.WeChat.SECRET)
                .replace("CODE", code);
        //发送请求获取token
        String result = HttpClientUtils.httpGet(getTokenUrl);
        //将结果转换成json对象
        JSONObject jo = JSONObject.parseObject(result);
        String access_token = jo.getString("access_token");
        String openid = jo.getString("openid");
        //通过openid去查wxuser表中有没有关联的信息
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //如果没有就去注册
        if (wxuser==null){
            //携带access_token和openid去binder绑定界面进行注册
            String url = "?access_token="+access_token+"&openid="+openid;
            return AjaxResult.getInstance().setResultObject(url).setMessage("binder");
        }
        //有关联的信息说明之前注册过了，直接免密登录
        //登录需要lf对象
        Long userId = wxuser.getUserId();
        Logininfo lf = userMapper.findLogininfoById(userId);
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,lf,30, TimeUnit.MINUTES);
//        //组装数据返回给前端(map组装数据)
//        HashMap<String, Object> hm = new HashMap<>();
//        hm.put("token",token);
//        //处理logininfo
//        lf.setType(null);
//        lf.setPassword(null);
//        lf.setSalt(null);
//        lf.setDisable(null);
//        hm.put("logininfo",lf);
        return AjaxResult.getInstance().setResultObject(loginSuccessHandler(lf));
    }

    @Override
    public AjaxResult wechatBinder(WeChatBinderDto dto) {
        //判断两次密码是否一致
        if(!dto.getPassword().equals(dto.getConfirmPassword())){
            throw new CustomException(ErrorCode.LOGIN_FAILED.getCode());
        }
        //判断用户新输入的账号是否存在
        User user = userMapper.findByPhone(dto.getPhone());
        if(user != null){
            throw new CustomException(ErrorCode.USER_ALREADY_EXIST.getCode());
        }
        //校验通过，保存注册信息三个表 logininfo user wxuser
        //封装loginInfo对象并保存
        String salt = StrUtils.getComplexRandomString(64);
        String password = MD5Utils.encrypByMd5(salt+dto.getPassword());
        Logininfo lf = initLoginInfo(dto,salt,password);
        logininfoMapper.add(lf);
        //封装user并保存
        user = loginInfo2User(lf);
        userMapper.add(user);
        //封装wxuser并保存
        //发送请求获取微信基本信息
        String getUserInfoUrl = Constant.WeChat.GET_USER_INFO
                .replace("ACCESS_TOKEN",dto.getToken())
                .replace("OPENID",dto.getOpenId());
        String res = HttpClientUtils.httpGet(getUserInfoUrl);
        Wxuser wxuser = JSONObject.parseObject(res, Wxuser.class);
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        //注册完了之后免密登录
        //存redis(key:uuid 值：logininfo)
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, lf, 30, TimeUnit.MINUTES);
//        //组装数据返回给前端(map组装数据)
//        HashMap<String, Object> hm = new HashMap<>();
//        hm.put("token", token);
//        //处理logininfo
//        lf.setType(null);
//        lf.setPassword(null);
//        lf.setSalt(null);
//        lf.setDisable(null);
//        hm.put("logininfo", lf);
        return AjaxResult.getInstance().setResultObject(loginSuccessHandler(lf));
    }
    private Logininfo initLoginInfo(WeChatBinderDto dto, String salt, String password) {
        Logininfo lf = new Logininfo();
        lf.setUsername(dto.getPhone());
        lf.setPhone(dto.getPhone());
        lf.setSalt(salt);
        lf.setPassword(password);
        lf.setType(1);
        lf.setDisable(1);
        return lf;
    }
    private User loginInfo2User(Logininfo lf){
        User user = new User();
        //bean拷贝，把相同字段的值拷贝到另一个对象的相同字段去
        BeanUtils.copyProperties(lf,user);
        user.setState(1);
        user.setCreateTime(new Date());
        user.setLogininfoId(lf.getId());
        return user;
    }

    /**
     * 登录成功处理
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        UserInfo userInfo = new UserInfo();
        Map<String, Object> map = new HashMap<>();
        userInfo.setLogininfo(logininfo);
        //判断当前用户是主站还是后端管理系统
        if(logininfo.getType() == 1){
            //单纯返回个人信息
            try {
                PrivateKey privateKey = RsaUtils
                        .getPrivateKey(FileCopyUtils
                                .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
                //加密得到token
                String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 60*24);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                map.put("token",token);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeySpecException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            //如果是后端，返回个人信息+权限信息
            List<String> sns = permissionMapper.findPermissionByLoginInfoId(logininfo.getId());
            List<Menu> menus = menuMapper.findMenuByLoginInfoId(logininfo.getId());
            userInfo.setPermissions(sns);
            userInfo.setMenus(menus);
            try {
                //获取私钥
                PrivateKey privateKey = RsaUtils
                        .getPrivateKey(FileCopyUtils
                                .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
                //加密得到token
                String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 60*24);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                map.put("logininfo",logininfo);
                map.put("token",token);
                map.put("permissions",sns);
                map.put("menus",menus);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeySpecException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }
}
